<template>
  <van-button
          v-if="isFollowed"
            class="follow-btn"
            round
            size="small"
            @click="onFollow"
            :loading='loading'
          >已关注</van-button>
          <van-button
          v-else
            class="follow-btn"
            type="info"
            color="#3296fa"
            round
            size="small"
            icon="plus"
            @click="onFollow"
            :loading='loading'
          >关注</van-button>
</template>
<script>
import { addFollow, deleteFollow } from '@/api/user'
export default {
  name: 'FollowUser',
  // 自定义v-model的数据名称
  model: {
    prop: 'isFollowed', // 默认是value
    event: 'update-is_followed' // 默认是input
  },
  props: {
    isFollowed: {
        type: Boolean,
        required: true
      },
      userId: {
        type: [Number, String, Object],
      required: true
      }
  },
  data () {
    return {
      loading: false
    }
  },
  methods: {
    async onFollow () {
     this.loading = true // 展示关注loading的状态
      try {
        if (this.isFollowed) {
        // 已关注，取消关注
            await deleteFollow(this.userId)
         } else {
          // 没有关注添加关注
          await addFollow(this.userId)
           }
          //  更新视图状态
          this.$emit('update-is_followed', !this.isFollowed)
          // this.$emit('update-is_followed', !this.value)
          // this.article.is_followed = !this.article.is_followed
       } catch (error) {
         let message = '操作失败，请稍后重试'
         console.log(error)
         if (error.response && error.response.status === 400) {
           message = '不能关注自己'
         }
        this.$toast(message)
      }
       this.loading = false // 关闭关注loading的状态
    }
  }
}
</script>
